<template>
  <el-container class="home-container">
    <!-- 头部区域 -->
    <el-header>
      <el-row :gutter="20">
        <el-col :span="8"
        ><img src="../assets/img/logo.jpg" alt=""/><span class="fami"
        ><i>CSI员工</i>之家</span
        ></el-col
        >
        <el-col :span="16">
          <el-row :gutter="5">
            <el-col :span="5">欢迎登录：{{ nickname }}</el-col>
            <el-col :span="9" id="time">{{ currentTime }}</el-col>
            <el-col :span="3"
            >
              <el-button type="primary" @click="dialogVisible = true"
              >修改密码
              </el-button
              >
            </el-col
            >
            <el-col :span="3"
            >
              <el-button type="success" @click="faceregdialogVisible = true"
              >人脸注册
              </el-button
              >
            </el-col
            >
            <el-col :span="3"
            >
              <el-button type="danger" @click="loginout"
              >退出登陆
              </el-button
              >
            </el-col
            >
          </el-row>
        </el-col>
      </el-row>
    </el-header>
    <!-- 页面主体区域 -->
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="200px">
        <!-- 侧边栏菜单 -->
        <el-menu
            background-color="#333744"
            text-color="#fff"
            active-text-color="#ffd04b"
            :unique-opened="true"
            router
        >
          <!-- 用户一级菜单 -->
          <el-submenu index="1">
            <!-- 一级菜单模板 -->
            <template slot="title">
              <!-- 图标 -->
              <i class="iconfont icon-user"></i>
              <!-- 文本 -->
              <span>用户管理</span>
            </template>

            <!-- 二级子菜单 -->
            <el-menu-item index="/user">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-s-grid"></i>
                <!-- 菜单项 -->
                <span>用户查询</span>
              </template>
            </el-menu-item>
            <el-menu-item index="/useradd">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-s-grid"></i>
                <!-- 菜单项 -->
                <span>添加用户</span>
              </template>
            </el-menu-item>
          </el-submenu>

          <!-- 部门一级菜单 -->
          <el-submenu index="2">
            <!-- 一级菜单模板 -->
            <template slot="title">
              <!-- 图标 -->
              <i class="iconfont icon-tijikongjian"></i>
              <!-- 文本 -->
              <span>部门管理</span>
            </template>

            <!-- 二级子菜单 -->
            <el-menu-item index="/deptlist">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-s-grid"></i>
                <!-- 菜单项 -->
                <span>部门查询</span>
              </template>
            </el-menu-item>
            <el-menu-item index="/deptadd">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-s-grid"></i>
                <!-- 菜单项 -->
                <span>添加部门</span>
              </template>
            </el-menu-item>
          </el-submenu>

          <!-- 职位一级菜单 -->
          <el-submenu index="3">
            <!-- 一级菜单模板 -->
            <template slot="title">
              <!-- 图标 -->
              <i class="iconfont icon-shangpin"></i>
              <!-- 文本 -->
              <span>职位管理</span>
            </template>
            <!-- 二级子菜单 -->
            <el-menu-item index="job">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>职位查询</span>
              </template>
            </el-menu-item>
            <el-menu-item index="jobadd">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>添加职位</span>
              </template>
            </el-menu-item>
          </el-submenu>

          <!-- 员工一级菜单 -->
          <el-submenu index="4">
            <!-- 一级菜单模板 -->
            <template slot="title">
              <!-- 图标 -->
              <i class="iconfont icon-danju"></i>
              <!-- 文本 -->
              <span>员工管理</span>
            </template>

            <!-- 二级子菜单 -->
            <el-menu-item index="/employee">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>员工查询</span>
              </template>
            </el-menu-item>
            <el-menu-item index="/employeeadd">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>添加员工</span>
              </template>
            </el-menu-item>
          </el-submenu>

          <!-- 公告一级菜单 -->
          <el-submenu index="5">
            <!-- 一级菜单模板 -->
            <template slot="title">
              <!-- 图标 -->
              <i class="iconfont icon-baobiao"></i>
              <!-- 文本 -->
              <span>公告管理</span>
            </template>

            <!-- 二级子菜单 -->
            <el-menu-item index="/notice">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>公告查询</span>
              </template>
            </el-menu-item>
            <el-menu-item index="/noticeadd">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>添加公告</span>
              </template>
            </el-menu-item>
          </el-submenu>

          <!-- 下载中心一级菜单 -->
          <el-submenu index="6">
            <!-- 一级菜单模板 -->
            <template slot="title">
              <!-- 图标 -->
              <i class="iconfont icon-baobiao"></i>
              <!-- 文本 -->
              <span>下载中心</span>
            </template>

            <!-- 二级子菜单 -->
            <el-menu-item index="/document">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>文档查询</span>
              </template>
            </el-menu-item>
            <el-menu-item index="/documentupload">
              <!-- 二级菜单模板 -->
              <template slot="title">
                <!-- 图标 -->
                <i class="el-icon-location"></i>
                <!-- 菜单项 -->
                <span>上传文档</span>
              </template>
            </el-menu-item>
          </el-submenu>

        </el-menu>
      </el-aside>
      <!-- 主体结构 -->
      <el-main>
        <router-view/>
      </el-main>
    </el-container>

    <!-- 修改密码对话框 -->
    <el-dialog
        title="修改密码"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
    >
      <el-form ref="form" :model="editpwd" label-width="80px" :rules="rules">
        <el-form-item label="新 密 码:" prop="newPassword">
          <el-input v-model="editpwd.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认密码:" prop="qrpwd">
          <el-input v-model="editpwd.qrpwd"></el-input>
        </el-form-item>
        <el-form-item label="当前密码:" prop="oldPassword">
          <el-input v-model="editpwd.oldPassword"></el-input>
        </el-form-item>
      </el-form>


      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 人脸注册 -->
    <el-dialog title="人脸注册" :visible.sync="faceregdialogVisible" width="30%" :before-close="handleClose">
      <div class="camera_outer">
        <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas
            style="display: none"
            id="canvasCamera"
            :width="videoWidth"
            :height="videoHeight"
        ></canvas>
        <div v-if="imgSrc" class="img_bg_camera" style="display: none">
          <img :src="imgSrc" alt="" class="tx_img"/>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="getCompetence()">打开摄像头</el-button>
        <el-button @click="stopNavigator()">关闭摄像头</el-button>
        <!-- <el-button @click="faceregdialogVisible = false">取 消</el-button> -->
        <!-- <el-button type="primary" @click="facereg">确 定</el-button> -->
        <el-button type="primary" @click="setImage" :disabled="!cameraOpened">注册</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
export default {
  created() {
    const userdata = JSON.parse(window.sessionStorage.getItem("userinfo"));
    console.log(userdata.username);
    this.nickname = userdata.username;
    console.log(window.sessionStorage.getItem("userinfo") + "：token中值");
  },
  data() {
    return {
      editpwd: {
        newPassword: "",
        qrpwd: "",
        oldPassword: "",
        ostrongpwd: "",
      },
      currentTime: "", // 用于存储当前时间
      nickname: "",
      cameraOpened: false, // 添加一个变量来标记摄像头是否开启
      dialogVisible: false,
      faceregdialogVisible: false,
      videoWidth: 300,
      videoHeight: 300,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,

      rules: {
        newPassword: [
          {required: true, message: "请输入新密码", trigger: "blur"},
          {
            min: 6,
            max: 12,
            message: "密码长度在 6 到 12 个字符之间",
            trigger: "blur",
          },
          // 其他规则如至少包含一个数字和一个字母等可以自行添加
        ],
        qrpwd: [
          {required: true, message: "请确认密码", trigger: "blur"},
          {validator: this.validateSamePassword, trigger: "blur"},
        ],
        oldPassword: [
          {required: true, message: "请输入当前密码", trigger: "blur"},
        ],
      },
    };
  },
  mounted() {
    this.updateTime(); // 组件挂载后更新当前时间
    setInterval(this.updateTime, 1000); // 每秒更新时间
  },
  methods: {
    validateSamePassword(rule, value, callback) {
      if (value !== this.editpwd.newPassword) {
        callback(new Error("确认密码与新密码不一致"));
      } else {
        callback();
      }
    },
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.editpwdhandle(); // 如果验证通过，调用修改密码的方法
        } else {
          this.$message.error("表单验证不通过，请检查输入"); // 如果验证不通过，显示错误信息
        }
      });
    },
    updateTime() {
      const now = new Date();
      const options = {
        year: "numeric",
        month: "numeric",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        weekday: "long",
        hour12: false,
      };
      this.currentTime = now.toLocaleString("zh-CN", options); // 设置当前时间，格式化为中文
    },
    async loginout() {
      try {
        const {data: res} = await this.$http.post("/users/logout");
        if (res.code === 200) {
          this.$message.success(res.message);
          window.sessionStorage.clear();
          this.$router.push("/login");
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
          .then(() => {
            done();
          })
          .catch(() => {
          });
    },
    async editpwdhandle() {
      try {
        // 确保 editpwd.oldPassword 和 editpwd.newPassword 已经有值
        const params = new URLSearchParams();
        params.append("oldPassword", this.editpwd.oldPassword);
        params.append("newPassword", this.editpwd.newPassword);
        const {data: res} = await this.$http.post("/users/updatePassword", params);
        if (res.code === 200) {
          this.dialogVisible = false;
          this.$message.success(res.message);
          // 清除token
          window.sessionStorage.clear();
          // 跳转到登录页面
          this.$router.push("/login");
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera");
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function () {
              _this.thisVideo.play();
              _this.cameraOpened = true; // 标记摄像头已打开
              _this.startFaceRecognition(); // 开始人脸识别
            };
          })
          .catch((err) => {
            console.log(err);
          });
    },
    startFaceRecognition() {
      // 这里可以实现人脸识别的逻辑
      // 例如：使用定时器来定期捕获视频帧进行识别
    },
    //  绘制图片（拍照功能）
    async setImage() {
      var _this = this;
      if (!_this.thisContext || !_this.cameraOpened) {
        return this.$message.error("请打开摄像头，人脸注册失败");
      }

      _this.thisContext.drawImage(
          _this.thisVideo,
          0,
          0,
          _this.videoWidth,
          _this.videoHeight
      );

      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image;
      const userdata = JSON.parse(window.sessionStorage.getItem("userinfo"));

      const params = {
        file: await _this.dataURLtoFile(image, userdata.id + ".png"),
      };

      const formData = new FormData();
      formData.append("file", params.file);

      // 重试请求的逻辑
      const maxRetries = 3;
      let attempt = 0;

      while (attempt < maxRetries) {
        try {
          const {data: res} = await this.$http.post("/face/reg", formData, {
            headers: {
              "Content-Type": "multipart/form-data"
            }
          });
          console.log(res);
          if (res.code === 200) {
            this.$message.success("注册成功");
            this.faceregdialogVisible = false; // 关闭注册对话框
            return;
          } else {
            console.error(res, "注册失败的res");
            if (res.data.error_code === 18) {
              // 超过请求限制，处理异常
              this.$message.error("请求频率过高，请稍后再试");
              return;
            } else {
              this.$message.error(res.message);
              return;
            }
          }
        } catch (error) {
          console.error("注册发生错误:", error);
          if (error.response && error.response.data) {
            // 如果错误码是18，则提前返回
            const errData = error.response.data;
            this.$message.error(errData.message || "注册失败，系统异常");
          } else {
            this.$message.error("注册过程中发生错误，请尝试再次操作");
          }
        }

        // 增加延迟，然后重试
        await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒再重试
        attempt++;
      }

      this.$message.error("重试达到上限，注册失败");
    },
    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime || 'image/png'});
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
    facereg() {
      this.faceregdialogVisible = false;
    },
    async faceregfn() {
      const res = await this.$http.post("/facereg", {id: 2});
      console.log(res);
      // this.faceregdialogVisible = true
      // this.getCompetence()
    },
  },
};
</script>

<style lang="less">
.home-container {
  height: 100%;
}

.el-header {
  line-height: 60px;
  color: #fff;
  background-color: #373d41;

  .el-button {
    float: right;
    margin-top: 15px;
  }
}

.el-aside {
  background-color: #333744;
}

.el-main {
  background-color: #eaedf1;
}

.iconfont {
  margin-right: 10px;
}

.el-form-item__label {
  font-size: 12px !important;
}

.el-menu-item {
  background-color: #35404d !important;
}

.el-submenu__title:hover {
  background: #138078 !important;
  color: #fff !important;
}

.el-menu-item.is-active {
  background: #3bc5bb !important;
  color: #fff !important;
}

.el-submenu__title.is-active {
  // background: #1c88cf !important;
  color: #fff !important;
}

.el-header .fl {
  float: left;
}

.el-header img {
  margin-top: -3px;
  vertical-align: middle;
}

.el-header .fami {
  color: #ff9a4c;
  font-size: 20px;
  font-weight: bold;
}

.el-header .fami i {
  font-style: normal;
  color: #3bc5bb;
  font-weight: bold;
}

.el-header .fr {
  float: right;
  width: 600px;
  height: 100%;
}

.camera_outer {
  position: relative;
  overflow: hidden;
  background-size: 100%;

  video {
    margin-left: 75px;
  }

  .btn_camera {
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.3);
    line-height: 50px;
    text-align: center;
    color: #ffffff;
  }

  .bg_r_img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }

  .img_bg_camera {
    position: absolute;
    right: 0;
    top: 0;

    img {
      width: 300px;
      height: 300px;
    }

    .img_btn_camera {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #ffffff;

      .loding_img {
        width: 50px;
        height: 50px;
      }
    }
  }
}
</style>